<template>
	<view class="dy-account">
		<view class="layout-header" :style="{ height: fixedTop + 'px' }">
			<DistributionNavBar rgb="#fff" leftColor="#000" title="我的抖音号" backgroundColor="transparent">
				<template slot="left">
					<image class="layout-header-image" :src="bankIcon" @click="clickBack" />
				</template>
			</DistributionNavBar>
		</view>
		<view class="before-bg" :style="{ marginTop: fixedTop + 'px' }"></view>
		<view class="after-bg">
			<view class="dy-account-remind flex">
				<view class="remind-icon"><image src="/static/images/third/img_ts_title@3x.png" /></view>
				<view class="remind-bg"><image src="/static/images/third/img_ts_bg@3x.png" /></view>
				<view class="remind-text">
					完善资料后达人才可申请探店哦~
					<br />
					抖音链接是关联订单的唯一凭证，请务必确保抖音链接准确！
				</view>
			</view>
			<view class="dy-account-list">
				<block v-if="accountData.length">
					<accountItem
						v-for="(item, index) in accountData"
						:key="item.id"
						@setDefaultFn="changeDefault(item, index)"
						@cancalBindFn="showCancleBind(item)"
						:listItem="item"
						:currIndex="defaultIndex"
						:selfIndex="index"
						@toDyFn="addBinding"
					></accountItem>
				</block>
				<view v-else class="dy-account-empty">
					<image src="/static/images/third/img_nopic@2x.png" />
				</view>
			</view>
			<view class="dy-account-action" @click="addBinding"><view class="btn">添加新抖音账号</view></view>
		</view>
		<!-- 二维码弹层 -->
		<dyPopup v-model="isPopupBind" :isDyBg="true" :showClose="true" @button1Click="saveCodeImage" :contentHeight="520">
			<view class="code-wapper common-wapper">
				<view class="title-text">抖音扫描二维码</view>
				<image :src="codeImage" show-menu-by-longpress class="image" />
				<view class="remind-box">
					<view class="remind-title">授权步骤：</view>
					<view class="flex remind-item col-center">
						<view class="num-dot">1</view>
						<text class="text-left">保存二维码至相册</text>
					</view>
					<view class="flex remind-item col-center">
						<view class="num-dot">2</view>
						<text class="text-left">打开抖音app，扫描‘相册’里的二维码</text>
					</view>
					<view class="flex remind-item col-center">
						<view class="num-dot">3</view>
						<text class="text-left">点击【授权绑定】--【同意】，即完成授权</text>
					</view>
				</view>
			</view>
		</dyPopup>
		<!-- 取消绑定弹层 -->
		<dyPopup v-model="isPopupCancle" :buttonNum="2" :buttonText="buttonTextArr" @button1Click="cancleBinding">
			<view class="cancle-wapper common-wapper">
				<view class="title-text">确认取消当前授权绑定</view>
				<view class="remind-text">如果已参与了达人任务获取了佣金，解绑会影响后续提现等操作，请慎重解绑</view>
			</view>
		</dyPopup>
	</view>
</template>

<script>
import accountItem from './components/accountItem.vue';
import DistributionNavBar from '@/components/distributionNavBar/indeHome';
import dyPopup from '@/components/dyPopup';
import { saveCodeImageCom } from '@/utils/common';
import { defaultImageUrl, isIos, getSystemInfo } from '@/utils';
import { dyAccountList, dyAccountUnbind, setDefaultAccount, checkDyAccountNum } from '@/api/third';
import { getDyAuthCode } from '@/utils';
import { mapGetters } from 'vuex';
const bankIcon = Object.freeze(`${defaultImageUrl}help/icon_navbar_back.png`);
// 顶部导航 rgba
const speed = 80;
const modelIsIos = isIos();
const { statusBarHeight } = getSystemInfo();
const fixedTop = Object.freeze((modelIsIos ? 44 : 48) + statusBarHeight);
export default {
	name: 'dyAccount',
	components: {
		accountItem,
		dyPopup,
		DistributionNavBar
	},
	data() {
		return {
			fixedTop,
			bankIcon,
			isSetDefault: false,
			accountData: [],
			isdyNum: false,
			isPopupBind: false, // 抖音账号二维码
			isPopupCancle: false, // 取消绑定
			defaultIndex: -1,
			codeImage: '',
			buttonTextArr: ['确认解绑', '取消'],
			actionId: '', //正在操作的id
			timer: null
		};
	},
	computed: {
		...mapGetters(['getDyCodeImage'])
	},
	watch: {
		isPopupBind(val) {
			console.log(val);
			if (val) {
				uni.stopPullDownRefresh();
				this.cicleNumFn();
			} else {
				clearTimeout(this.timer);
			}
		},
		accountData(val1, val2) {
			console.log(val1, val2);
			if (val1.length !== val2.length) {
				this.setDefaultIndex();
			}
		}
	},
	onLoad() {
		this.getDyAccountList();
	},
	methods: {
		// 新增绑定
		addBinding() {
			const { getDyCodeImage = '' } = this;
			if (!getDyCodeImage) {
				getDyAuthCode().then((res) => {
					console.log(res);
					this.isPopupBind = true;
					this.codeImage = res;
				});
			} else {
				this.codeImage = getDyCodeImage;
				this.isPopupBind = true;
			}
		},
		// 显示取消绑定
		showCancleBind(item = {}) {
			const { id = '' } = item;
			if (id) {
				this.actionId = id;
				this.isPopupCancle = true;
			} else {
				this.showToastFn('当前数据无效');
			}
		},
		// 取消绑定
		cancleBinding() {
			const { actionId = '', showToastFn, getDyAccountList, setDefaultIndex } = this;
			uni.showLoading({
				title: '处理中…'
			});
			dyAccountUnbind({ id: actionId })
				.then((res = {}) => {
					console.log(res);
					const { code } = res;
					if (code === 200) {
						uni.hideLoading();
						this.isPopupCancle = false;
						showToastFn('取消成功');
						getDyAccountList();
						// this.$nextTick(()=>{
						// 	setDefaultIndex()
						// })
					} else {
						showToastFn('取消失败');
					}
				})
				.catch((err) => {
					console.log(err);
					this.isPopupCancle = false;
					uni.hideLoading();
				});
		},
		// 改变默认设置
		changeDefault(row = {}, index = 0) {
			const { showToastFn, getDyAccountList } = this;
			const { id = '', isDefault = 0, dyUrl = '' } = row;
			if (isDefault) {
				showToastFn('已是默认');
				return;
			}
			if (!dyUrl) {
				showToastFn('该抖音账号资料未完善不能设为默认');
				return;
			}
			this.defaultIndex = index;
			setDefaultAccount({ id: id })
				.then((res = {}) => {
					console.log(res);
					const { code } = res;
					if (code === 200) {
						showToastFn('设置成功');
						setTimeout(() => {
							getDyAccountList(false);
						}, 500);
					} else {
						showToastFn('设置失败');
					}
				})
				.catch((err) => {
					console.log(err);
					this.isPopupCancle = false;
				});
		},
		// 初始化默认值
		setDefaultIndex() {
			let computeIndex = [];
			computeIndex = this.accountData
				.map((item, index) => {
					if (item.isDefault) {
						return index;
					}
				})
				.filter((getIndex) => getIndex !== undefined);
			if (computeIndex.length) {
				this.defaultIndex = computeIndex[0];
			} else {
				this.defaultIndex = -1;
			}
			console.log(computeIndex, this.defaultIndex);
			// this.defaultIndex = computeIndex;
			// console.log(this.defaultIndex)
		},
		// 保存二维码
		saveCodeImage() {
			const self = this;
			saveCodeImageCom(this.codeImage, function () {
				self.isPopupBind = false;
			});
		},
		// 获取抖音账号列表
		getDyAccountList(isShowLoading = true) {
			if (isShowLoading) {
				uni.showLoading({
					title: '处理中…'
				});
			}
			// if(this.isPopupBind){
			// 	uni.stopPullDownRefresh()
			// }
			dyAccountList()
				.then((res = {}) => {
					const { data = [], code } = res;
					if (code === 200) {
						this.accountData = data;
						this.$nextTick(() => {
							this.setDefaultIndex();
							uni.hideLoading();
						});
					} else {
						this.showToastFn('数据异常');
					}
					uni.stopPullDownRefresh();
					console.log(res);
				})
				.catch(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				});
		},
		showToastFn(title = '', icon = false, status = 'success') {
			uni.showToast({
				title: title || '提示信息',
				icon: icon ? status : 'none'
			});
		},
		// 轮循查询账号列表状态
		cicleNumFn() {
			let accountNum = this.accountData.length;
			checkDyAccountNum(accountNum).then((res = {}) => {
				const { data = { blnNew: false } } = res;
				if (!data.blnNew) {
					this.timer = setTimeout(() => {
						this.cicleNumFn();
					}, 3000);
				} else {
					clearTimeout(this.timer);
					this.getDyAccountList();
				}
			});
		},
		//返回上一页
		clickBack() {
			// uni.navigateBack();
			uni.switchTab({
				url: '/pages/tabBar/PersonalCenter'
			});
		}
	},
	onHide() {
		clearTimeout(this.timer);
	},
	onUnload() {
		clearTimeout(this.timer);
	},
	// 上拉
	onPullDownRefresh() {
		this.getDyAccountList();
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';
.dy-account {
	width: 100%;
	height: calc(100vh - 120rpx);
	overflow-y: scroll;
	background: #f6f6f6;
	position: relative;
	// padding: 20rpx;
	@include Db_iosBottomDistance(20rpx);
	&-remind {
		width: 100%;
		padding: 20rpx;
		background: #fff0e7;
		border-radius: 24rpx;
		z-index: 3;
		border: 1px solid rgba(245, 137, 78, 0.2);
		position: relative;
		image {
			width: 100%;
			height: 100%;
		}
		.remind-icon {
			flex-shrink: 1;
			width: 72rpx;
			height: 76rpx;
			margin-right: 16rpx;
			image {
				width: 100%;
				height: 100%;
			}
		}
		.remind-bg {
			position: absolute;
			z-index: 0;
			left: 0;
			top: 0;
			width: 96rpx;
			height: 96rpx;
		}
		.remind-text {
			width: calc(100% - 72rpx);
			font-size: 24rpx;
			color: #ff6b11;
		}
	}
	&-list {
		margin-top: 30rpx;
	}
	&-action {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background: #ffffff;
		padding: 16rpx 28rpx;
		box-shadow: 0px 0px 4px 0px rgba(51, 51, 51, 0.14);
		@include Db_iosBottomDistance(10rpx);
		// cursor: pointer;
		.btn {
			background: #ff6b11;
			border-radius: 24rpx;
			width: 100%;
			height: 88rpx;
			text-align: center;
			line-height: 88rpx;
			color: #ffffff;
		}
	}
	&-empty {
		width: 480rpx;
		height: 320rpx;
		margin: 240rpx auto 0;
		image {
			width: 100%;
			height: 100%;
		}
	}
}

.before-bg {
	width: 100%;
	height: 200rpx;
	left: 0;
	// background: linear-gradient(180deg, #fff7f2 0%, #f6f6f6 100%);
	z-index: 1;
}
.after-bg {
	margin-top: -200rpx;
	padding: 20rpx;
}
.layout {
	&-header {
		position: fixed;
		left: 0;
		top: 0;
		z-index: 9999;
		background: transparent;

		&-image {
			width: 40rpx;
			height: 40rpx;
			display: block;
		}
	}
}
</style>
